package com.voodoo.serialport.util;

/**
 * Author: voodoo
 * CreateDate: 2021/05/23
 * Description:
 */
public class ByteUtils {

    public static int isOdd(int num) {
        return num & 0x1;
    }

    public static int HexToInt(String inHex) {
        return Integer.parseInt(inHex, 16);
    }

    public static byte HexToByte(String inHex) {
        return (byte) Integer.parseInt(inHex, 16);
    }

    public static byte[] hexToByteArr(String hex) {
        int hexLen = hex.length();
        byte[] result;
        if (isOdd(hexLen) == 1) {
            hexLen++;
            result = new byte[hexLen / 2];
            hex = "0" + hex;
        } else {
            result = new byte[hexLen / 2];
        }
        int j = 0;
        for (int i = 0; i < hexLen; i += 2) {
            result[j] = HexToByte(hex.substring(i, i + 2));
            j++;
        }
        return result;
    }

    /**
     * 单个byte转Hex的字符
     *
     * @param inByte 字节
     * @return String 两位字符，byte<16 的话会添加上0，凑齐两位
     */
    public static String byteToHex(Byte inByte) {
        byte[] bytes = {inByte};
        return byteArrToHex(bytes);
    }
    /**
     * 将byte数组转换为Hex字符串
     *
     * @param bytes Byte数组
     * @return Hex格式的字符串
     */
    public static String byteArrToHex(byte[] bytes) {
        return byteArrToHex(bytes, bytes.length);
    }


    /**
     * 将byte数组转换成Hex字符串
     *
     * @param bytes 要转换的byte数组
     * @param size  要转换的长度
     * @return 转换后的字符串（转大写之后的）
     */
    public static String byteArrToHex(byte[] bytes, int size) {
        StringBuilder stringBuilder = new StringBuilder();
        if (bytes == null || bytes.length <= 0 || bytes.length < size) {
            return null;
        }
        for (int i = 0; i < size; i++) {
            String hexString = Integer.toHexString(bytes[i] & 0xFF);
            if (hexString.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hexString);
            stringBuilder.append(" ");
        }
        return stringBuilder.toString().toUpperCase().trim();
    }
    /**
     * 将byte数组转换成Hex字符串
     *
     * @param bytes 要转换的byte数组
     * @param size  要转换的长度
     * @return 转换后的字符串（转大写之后的）
     */
    public static String byteArrToHex(byte[] bytes,int start, int size) {
        StringBuilder stringBuilder = new StringBuilder();
        if (bytes == null || bytes.length <= 0 || bytes.length < size) {
            return null;
        }
        for (int i = start; i < size; i++) {
            String hexString = Integer.toHexString(bytes[i] & 0xFF);
            if (hexString.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hexString);
            stringBuilder.append(" ");
        }
        return stringBuilder.toString().toUpperCase().trim();
    }

}
